"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Alert, Button, Card, Form, Input, Radio, Space, Typography } from "antd";
import { LockOutlined, UserOutlined, MailOutlined } from "@ant-design/icons";
import Link from "next/link";
import { api } from "~/trpc/react";

interface RegisterFormData {
  name: string;
  email: string;
  password: string;
  role: "TEACHER" | "STUDENT";
}

export default function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const callbackUrl = searchParams.get("callbackUrl");

  const registerMutation = api.auth.register.useMutation({
    onSuccess: () => {
      // 注册成功后跳转到登录页，并保持 callbackUrl
      router.push(`/login${callbackUrl ? `?callbackUrl=${callbackUrl}` : ""}`);
    },
    onError: (error) => {
      setError(error.message);
    },
  });

  const onFinish = async (values: RegisterFormData) => {
    try {
      setLoading(true);
      setError(null);
      await registerMutation.mutateAsync(values);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card style={{ width: 400 }}>
      <Space direction="vertical" size="large" style={{ width: "100%" }}>
        <Typography.Title level={2} style={{ textAlign: "center", marginBottom: 0 }}>
          注册
        </Typography.Title>

        {error && <Alert type="error" message={error} />}

        <Form
          name="register"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            name="name"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input prefix={<MailOutlined />} placeholder="邮箱" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码长度不能小于6位" },
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="role"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Radio.Group>
              <Radio value="TEACHER">我是老师</Radio>
              <Radio value="STUDENT">我是学生</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              注册
            </Button>
          </Form.Item>
        </Form>

        <Typography.Text style={{ textAlign: "center", display: "block" }}>
          已有账号？{" "}
          <Link 
            href={`/login${callbackUrl ? `?callbackUrl=${callbackUrl}` : ""}`}
          >
            立即登录
          </Link>
        </Typography.Text>
      </Space>
    </Card>
  );
}